@using Radzen.Blazor

<div class="rz-view rz-day-view">
    <div class="rz-view-header">
        <div class="rz-slot-hour-header"></div>
        <div class="rz-slot-header">
            @StartDate.ToString("ddd", Scheduler.Culture)
        </div>
    </div>
    <div class="rz-view-content">
        <Hours Start=@StartTime End=@EndTime TimeFormat=@TimeFormat MinutesPerSlot=@MinutesPerSlot />
        <div class="rz-slots">
            <DaySlotEvents MinutesPerSlot=@MinutesPerSlot StartDate=@StartDate EndDate=@EndDate Appointments=@Appointments />
            @for (var date = StartDate; date < EndDate; date = date.AddMinutes(MinutesPerSlot))
            {
                var slotDate = date;
                <div @onclick=@(args => OnSlotClick(slotDate)) @attributes=@Attributes(date)></div>
            }
        </div>
    </div>
</div>

@code {
    [Parameter]
    public DateTime StartDate { get; set; }

    [Parameter]
    public TimeSpan StartTime { get; set; }

    [Parameter]
    public DateTime EndDate { get; set; }

    [Parameter]
    public TimeSpan EndTime { get; set; }

    [Parameter]
    public string TimeFormat { get; set; }

    [Parameter]
    public int MinutesPerSlot { get; set; }

    [Parameter]
    public IList<AppointmentData> Appointments { get; set; }

    [CascadingParameter]
    public IScheduler Scheduler { get; set; }

    private AppointmentData[] AppointmentsInSlot(DateTime start, DateTime end)
    {
        if (Appointments == null)
        {
            return Array.Empty<AppointmentData>();
        }

        return Appointments.Where(item => Scheduler.IsAppointmentInRange(item, start, end)).OrderBy(item => item.Start).ThenByDescending(item => item.End).ToArray();
    }

    async Task OnSlotClick(DateTime date)
    {
        await Scheduler.SelectSlot(date, date.AddMinutes(MinutesPerSlot), AppointmentsInSlot(date, date.AddMinutes(MinutesPerSlot)));
    }

    IDictionary<string, object> Attributes(DateTime date)
    {
        var attributes = Scheduler.GetSlotAttributes(date, date.AddMinutes(MinutesPerSlot));
        attributes["class"] = ClassList.Create("rz-slot").Add("rz-slot-minor", (date.Minute / MinutesPerSlot) % 2 == 1).Add(attributes).ToString();
        return attributes;
    }
} 